package org.sxm.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.sxm.cloud.dto.order.OrderDTO;
import org.sxm.cloud.entity.order.OrderEntity;
import org.sxm.cloud.exception.BizException;
import org.sxm.cloud.service.IOrderService;

import java.util.ArrayList;
import java.util.List;

@RefreshScope //Nacos动态刷新配置
@RestController
public class OrderController {

    @Autowired
    private IOrderService orderService;

    /**
     * 限流后续操作方法
     * @param e
     * @return
     */
    public static OrderEntity getOrderFailBack( Integer id ,BlockException e) {
        System.out.println("查询订单ID=:"+id);
        throw new BizException("系统繁忙，请您稍后再试!");
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/order/{id}")
    @SentinelResource(value = "getOrderResource",blockHandler = "getOrderFailBack",blockHandlerClass = OrderController.class)
    public OrderEntity getOrder(@PathVariable("id") Integer id) {
        if (id <= 0) {
            throw new BizException("参数错误");
        }
        OrderEntity orderEntity = orderService.getByOrderId(id);
        return orderEntity;
    }

    /**
     * 查询订单列表
     *
     * @param
     * @return
     */
    @GetMapping("/order/list")
    public List<OrderEntity> listOrder() {
        System.out.println("查询订单列表");
        List<OrderEntity> list = new ArrayList<>();
        OrderEntity order = orderService.getByOrderId(1);
        list.add(order);
        return list;
    }


    /**
     * 保存订单详情
     *
     * @param order
     * @return
     */
    @PostMapping("/order/add")
    public String addOrder(@RequestBody OrderDTO order) {
        orderService.addOrder(order);
        return "保存订单成功";
    }

    /**
     * 订单支付更新订单状态
     * @param orderId
     * @return
     */
    @PostMapping("/order/pay")
    public String updateOrder(@RequestParam("orderId")Integer orderId) {
        orderService.updateOrderPayStatus(orderId);
        return "订单更新成功";
    }


}
